#!/bin/env python
#-*- coding:utf-8 -*-
#多台服务器内存监控报警
author="将军"

import os
import re
import sys
import time
import urllib
import smtplib
import paramiko
import urlparse
import traceback
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

#使用163邮箱发送报警
def sendMail(subject,msg,toaddr,fromaddr,smtpaddr,password):
    '''
    subject=主题,
    msg=信息
    toaddr=收件人
    fromaddr=发件人
    smtpaddr=SMTP服务器地址
    password=密码
    '''
    mail_msg=MIMEMultipart()
    #处理编码
    if not isinstance(subject,unicode):
        subject=unicode(subject,'utf-8')
    #邮件标题
    mail_msg['Subject']=subject
    #发件人
    mail_msg['From']=fromaddr
    #收件人
    mail_msg['To']=toaddr
    mail_msg.attach(MIMEText(msg,'html',"utf-8"))
    try:
        s=smtplib.SMTP()
        s.connect(smtpaddr,25)
        s.starttls()
        s.login(fromaddr,password)
        s.sendmail(fromaddr,toaddr,mail_msg.as_string())
        s.quit()
        print "邮件发送成功!"
    except Exception as e:
        print "Error:unable to send email"
        print traceback.format_exc()

#登陆服务器
def loginServer(data):
    #创建连接对象
    server=paramiko.SSHClient()
    #设置安全协议
    server.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    #登陆服务器
    server.connect(hostname=data['hostname'],username=data['username'],password=data['password'],port=data['port'])
    return server

#查看系统内存信息
def viewSystemMemeory(server):
    #执行命令查看内存信息
    stdin,stdout,stderr=server.exec_command('free -m')
    rst=stdout.read()
    return rst

#处理数据并计算使用率
def memoryUsageInfo(rst):
    rst_list=re.split(r'\n',rst)
    mem=re.split(r' ',rst_list[1])
    while '' in mem:
        mem.remove('')
    swap=re.split(r' ',rst_list[2])
    while '' in swap:
        swap.remove('')
    mem_total=mem[1]
    mem_used=mem[2]
    mem_free=mem[3]
    #mem_usage="{}{}".format(round(float(mem_used)/float(mem_total),4)*100,"%")
    mem_usage=round(float(mem_used)/float(mem_total),4)*100
    return mem_usage,mem_free
    
servers=[{"hostname":"192.168.3.8","username":"root","password":"junping","port":22},
         {"hostname":"192.168.3.15","username":"root","password":"junping","port":22}]
fromaddr="这里用自己的163邮箱"
password="这里用自己的163邮箱密码"
smtpaddr="smtp.163.com"
toaddr=["这里用自己的QQ邮箱"]
while True:
    for data in servers:
        server=loginServer(data)
        rst=viewSystemMemeory(server)
        mem_usage,mem_free=memoryUsageInfo(rst)
        print("主机%s的内存使用率:%s" %(data['hostname'],mem_usage))
        print('剩余内存:%sM' %mem_free)
        if mem_usage > 10:
            subject="系统内存占用率过高报警!"
            mem_usage_percent="{}{}".format(mem_usage,"%")
            msg="系统内存占用率超过阈值,当前占用率位:%s" %mem_usage_percent
            sendMail(subject,msg,toaddr[0],fromaddr,smtpaddr,password)
        time.sleep(0.5)
    time.sleep(5)
